<?php

namespace App\Http\Controllers;

use App\Exceptions\ApiException;
use App\Http\Requests\BookCatalogRequest;
use App\Imports\BatchUnitProCatalogImport29;
use App\Imports\BatchUnitProCatalogImport8;
use App\Imports\BatchUnitProCatalogImportLY;
use App\Imports\BookCatalogImport29;
use App\Imports\BookCatalogImport8;
use App\Imports\BookCatalogImportLY;
use App\Models\PartCompany;
use App\Models\Project;
use App\Models\ProjectClassify;
use App\Services\AttachmentService;
use App\Services\BaseService;
use App\Services\BookCatalogService;
use App\Services\BookTitleService;
use App\Services\CommonService;
use App\Services\ProjectService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 卷内目录 控制器类
 * Class BookCatalogController
 * @package App\Http\Controllers
 */
class BookCatalogController extends Controller
{
    public $bookCatalogService;
    public $bookTitleService;
    public $projectService;

    public function __construct(BookCatalogService $bookCatalogService, BookTitleService $bookTitleService, ProjectService $projectService)
    {
        parent::__construct();
        $this->bookCatalogService = $bookCatalogService;
        $this->bookTitleService   = $bookTitleService;
        $this->projectService     = $projectService;
    }

    /**
     * 卷内目录列表
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/3/2 15:16
     */
    public function index(Request $request): JsonResponse
    {
        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = $request->input('project_classify_id');
        $bookTitleId       = $request->input('book_title_id');
        $keyword           = $request->input('keyword', '');
        $list              = $this->bookCatalogService->getList($partCompanyId, $projectClassifyId, $bookTitleId, $keyword);

        return $this->success($list);
    }

    /**
     * 卷内重新排序
     */
    public function sortAgain(Request $request): JsonResponse
    {
        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = $request->input('project_classify_id');
        $bookTitleId       = $request->input('book_title_id');
        $serialNoIds       = redis()->get("serialNoIds:{$partCompanyId}:$projectClassifyId}:{$bookTitleId}");
        $serialNoIds       = json_decode($serialNoIds, true);
        $serialNos         = array_column($serialNoIds, 'serial_no');
        if (!(new BookCatalogService())->checkSerialNo($serialNos)) { //如果序号不合法，才进行排序
            $bookCatalogInstance = CommonService::getBookCatalogInstance($partCompanyId, $projectClassifyId);
            foreach ($serialNoIds as $key => &$val) {
                $bookCatalogInstance->where('id', $val['id'])->update(['serial_no' => $key + 1]);
            }
        }

        return $this->success('', '操作成功！');
    }

    /**
     * 添加卷内目录
     *
     * @param BookCatalogRequest $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/3/19 10:26
     */
    public function store(BookCatalogRequest $request): JsonResponse
    {
        $params = $request->all();
        $result = $this->bookCatalogService->addNewData($params);
        if (!$result) {
            return $this->error('添加失败！');
        }

        return $this->success('', '添加成功！');
    }

    /**
     * 更新一条信息，传哪些字段就会更新哪些字段
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/3/19 10:27
     */
    public function update(Request $request): JsonResponse
    {
        $params = $request->all();
        if (!BookTitleService::isAllowOperate($request->input('part_company_id'))) {
            return $this->error('无权修改！');
        }
        if (empty($params['serial_no'])) {
            return $this->error('序号不能为0');
        }
        if (!$this->bookCatalogService->updateData($params)) {
            return $this->error('修改失败！');
        }

        return $this->success('', "修改成功！");
    }

    /**
     * 批量替换
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/3/19 10:27
     */
    public function batchReplace(Request $request): JsonResponse
    {
        $params = $request->all();

        $this->bookCatalogService->batchReplace($params);

        return $this->success('', '替换成功！');
    }

    /**
     * 问题标记
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ApiException
     * @author: lxk
     * @date: 2024/3/19 10:27
     */
    public function problemMark(Request $request): JsonResponse
    {
        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = $request->input('project_classify_id');
        $problem           = format_str($request->input('problem'));
        $ids               = to_array($request->input('ids'));

        $bookCatalogInstance = $this->bookCatalogService->getBookCatalogInstance($partCompanyId, $projectClassifyId);
        if (!$bookCatalogInstance->whereIn('id', $ids)->update(['problem' => $problem])) {
            return $this->error('标记失败！');
        }
        CommonService::addProjectActionLog("卷内问题标记:{$problem}", implode(',', $ids), $partCompanyId, $projectClassifyId);

        return $this->success('', '标记成功！');
    }

    /**
     * 问题已解决
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ApiException
     * @author: lxk
     * @date: 2024/3/19 10:27
     */
    public function problemResolved(Request $request): JsonResponse
    {
        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = $request->input('project_classify_id');
        $id                = $request->input('id');

        $bookCatalogInstance = $this->bookCatalogService->getBookCatalogInstance($partCompanyId, $projectClassifyId);
        $bookCatalog         = $bookCatalogInstance->where('id', $id)->first();
        $problem             = $bookCatalog->problem;
        if (!$bookCatalogInstance->where('id', $id)->update(['problem' => ''])) {
            return $this->error('操作失败！');
        }
        CommonService::addProjectActionLog("问题已解决:{$problem}", $id, $partCompanyId, $projectClassifyId);

        return $this->success('', '操作成功！');
    }

    /**
     * 给单个卷内导入 pdf (若干个)
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ApiException
     * @throws \OSS\Http\RequestCore_Exception
     * @author: lxk
     * @date: 2024-12-13 14:10
     */
    public function addPdf(Request $request): JsonResponse
    {
        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = $request->input('project_classify_id');
        $bookCatalogId     = $request->input('book_catalog_id');
        $file              = $request->file('file');
        $uploadResult      = (new AttachmentService())->upload($file, 'oss', $partCompanyId, $projectClassifyId);
        if (!$this->bookCatalogService->addSomePdfs($partCompanyId, $projectClassifyId, $bookCatalogId, $uploadResult)) {
            return $this->error('添加失败~');
        }

        return $this->success('', '添加PDF成功！');
    }

    /**
     * 删除 PDF
     *
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Exceptions\ApiException
     * @author: lxk
     * @date: 2024/3/19 10:22
     */
    public function delPdf(Request $request): JsonResponse
    {
        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = $request->input('project_classify_id');
        $pdfId             = $request->input('pdf_id');

        $this->bookCatalogService->delPdf($partCompanyId, $projectClassifyId, $pdfId);

        return $this->success('', '删除成功！');
    }

    /**
     * 点击查看pdf,返回多个pdf路径数组
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/3/19 10:29
     */
    public function showPdfs(Request $request): JsonResponse
    {
        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = $request->input('project_classify_id');
        $bookCatalogId     = $request->input('book_catalog_id');

        $list = $this->bookCatalogService->getPdfList($partCompanyId, $projectClassifyId, $bookCatalogId);

        return $this->success($list);
    }

    /**
     * 导入数据
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/3/19 10:24
     */
    public function import(Request $request): JsonResponse
    {
        CommonService::isFileValid($request); //验证文件是否合法

        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = $request->input('project_classify_id');
        $batchUnit         = $request->input('batch_unit', 0);
        $combinationId     = $this->projectService->getDossierCombination($partCompanyId);
        if (empty($projectClassifyId) || $projectClassifyId == 'undefined') {
            return $this->error('请刷新下页面~');
        }
        $importCountKey = get_rand_str('import_catalog_count');
        redis()->setex($importCountKey, 1800, 0); //导入一个卷内excel，用时最大30分钟
        switch ($combinationId) { //用的哪种卷内格式
            case 3: //兰渝格式
                $batchUnit == 1
                    ? Excel::import(new BatchUnitProCatalogImportLY($partCompanyId, $projectClassifyId, $importCountKey), $request->file('file'))
                    : Excel::import(new BookCatalogImportLY($partCompanyId, $projectClassifyId, $importCountKey), $request->file('file'));
                break;
            case 2: //普通8号文格式
                $batchUnit == 1
                    ? Excel::import(new BatchUnitProCatalogImport8($partCompanyId, $projectClassifyId, $importCountKey), $request->file('file'))
                    : Excel::import(new BookCatalogImport8($partCompanyId, $projectClassifyId, $importCountKey), $request->file('file'));
                break;
            default: //默认29文格式
                $batchUnit == 1
                    ? Excel::import(new BatchUnitProCatalogImport29($partCompanyId, $importCountKey), $request->file('file'))
                    : Excel::import(new BookCatalogImport29($partCompanyId, $projectClassifyId, $importCountKey), $request->file('file'));
                break;
        }
        $count = redis()->get($importCountKey) ?: 0;
        $event = $batchUnit == 1 ? "多单位工程导入卷内数据:{$count}条" : "导入卷内数据:{$count}条";
        CommonService::addProjectActionLog($event, 0, $partCompanyId, $projectClassifyId);
        if (empty($count)) return $this->error('导入【0】条数据，请下载模板对照！确认单元格所在行是否合并，档案号后面的冒号是否是中文');

        return $this->success('', '成功导入【' . $count . '】条数据');
    }

    /**
     * 是否图纸
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ApiException
     * @author: lxk
     * @date: 2024/3/19 10:24
     */
    public function isPic(Request $request): JsonResponse
    {
        $partCompanyId       = $request->input('part_company_id');
        $projectClassifyId   = $request->input('project_classify_id');
        $id                  = $request->input('id');
        $isPic               = $request->input('is_pic', 0);
        $bookCatalogInstance = $this->bookCatalogService->getBookCatalogInstance($partCompanyId, $projectClassifyId);
        if (!$bookCatalogInstance->where('id', $id)->update(['is_pic' => $isPic])) {
            return $this->error('操作失败！');
        }
        $isPic = $isPic ? '是' : '否';
        CommonService::addProjectActionLog("修改图纸为:{$isPic}", $id, $partCompanyId, $projectClassifyId);

        return $this->success('', '操作成功！');
    }

    /**
     * 检查卷内
     *
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Exceptions\ApiException
     * @author: lxk
     * @date: 2024/3/9 16:36
     */
    public function check(Request $request): JsonResponse
    {
        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = $request->input('project_classify_id');
        $bookTitleId       = $request->input('book_title_id');

        $bookTitleInstance   = CommonService::getBookTitleInstance($partCompanyId, $projectClassifyId);
        $bookCatalogInstance = CommonService::getBookCatalogInstance($partCompanyId, $projectClassifyId);
        $combinationId       = (new ProjectService())->getDossierCombination($partCompanyId, $projectClassifyId);

        $this->bookCatalogService->checkBookCatalogData($bookTitleInstance, $bookCatalogInstance, $bookTitleId, $combinationId);

        $problemCount = BookCatalogService::getProblemCatalogCount($bookCatalogInstance, $bookTitleId);
        $msg          = $problemCount ? "检查完毕！共发现【{$problemCount}】个异常" : "检查完毕！没发现异常";

        return $this->success('', $msg);
    }

    /**
     * 回收站列表 （进行软删除的数据）
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/3/19 10:25
     */
    public function recycle(Request $request): JsonResponse
    {
        $data = $this->bookCatalogService->getRecycles($request);

        return $this->success($data);
    }

    /**
     * 批量软删除，ids可以是以","逗号分割的字符串，也可以是数组形式
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ApiException
     * @author: lxk
     * @date: 2024/3/19 10:25
     */
    public function destroyMore(Request $request): JsonResponse
    {
        $bookCatalogIds    = to_array($request->input('ids'));
        $partCompanyId     = $request->input('part_company_id');
        $projectClassifyId = $request->input('project_classify_id');
        $bookTitleId       = $request->input('book_title_id');

        if (!$this->bookCatalogService->delData($partCompanyId, $projectClassifyId, $bookTitleId, $bookCatalogIds)) {
            return $this->error('', '删除失败');
        }

        return $this->success('', '删除成功');
    }

}
